﻿namespace Leetcode.N0899;

public class Solution
{
    public string OrderlyQueue(string s, int k)
    {

        if (k > 1)
        {
            return new string(s.OrderBy(_ => _).ToArray());
        }

        var minCharIndex = 0;

        for (int i = 1; i < s.Length; i++)
        {
            if (s[i] < s[minCharIndex])
            {
                minCharIndex = i;

            }
            else if (s[i] == s[minCharIndex])
            {
                for (int j = i + 1; (j < s.Length || j % s.Length < i); j++)
                {
                    var targetIndex = (minCharIndex + (j - i)) % s.Length;
                    var sourceChar = s[j % s.Length];
                    var targetChar = s[targetIndex];
                    if (sourceChar > targetChar)
                    {
                        break;
                    }
                    else if (sourceChar < targetChar)
                    {
                        minCharIndex = i;
                        break;
                    }
                }
            }
        }

        if (minCharIndex == 0)
        {
            return s;
        }

        return s.Substring(minCharIndex) + s.Substring(0, minCharIndex);
    }
}
